package com.cmcc.pcap.packet.udp.udp.xdr;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.cmcc.pcap.packet.udp.UdpPacketDecorator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.cmcc.packet.entity.UdpEntity;
import com.cmcc.pcap.packet.udp.UdpConnection;
import com.cmcc.pcap.packet.util.DateUtil;
import com.cmcc.pcap.packet.util.PacketAnalysisConfig;

import org.pcap4j.packet.UdpPacket;

public class UdpXdrGenerate {

	private static Logger logger = LogManager.getLogger(com.cmcc.pcap.packet.udp.udp.xdr.UdpXdrGenerate.class);

	public List<UdpEntity> generate(UdpConnection udpConnection,String taskId) {
		List<UdpEntity> udpEntityList = new ArrayList<UdpEntity>();
		logger.debug("this is udp xdr generate !");
		UdpEntity udpEntity = new UdpEntity();
		udpEntity.setTaskId(Integer.parseInt(taskId));
		udpEntity.setType("UDP");

		ArrayList<UdpPacket> altemp = new ArrayList<UdpPacket>();
		Integer altemp_length = 0;
		for(UdpPacketDecorator upt:udpConnection.al){
			if(upt.udpPacket.getRawData().length > 0){
				altemp.add(upt.udpPacket);
				++altemp_length;
			}
			if(altemp_length == 8)
				break;
		}

		//业务识别
		udpEntity.setUdpPackets(altemp);
//		Environment environment = ProtocolSpringContextUtils.getBean("environment");
//		String systemName = environment.getProperty("system.name");
//		String appDistinguishPath = environment.getProperty("file.path.root");//集团规则库目录
//
//		if("awareness".equalsIgnoreCase(systemName)) {
//			AppDistinguish appDistinguish = new AppDistinguish();
//			Map<String,Object> pathMap = appDistinguish.getAppDistinguishPaths(appDistinguishPath);
//			Map<String,String> map = appDistinguish.udpAppDistinguishPcap4j(altemp, (String)pathMap.get("protolistPath"),(List<String>)pathMap.get("protodatList"));
//			if(map!=null) {
//				udpEntity.setAppTypeCd(map.get("appType"));
//				udpEntity.setAppSubTypeCd(map.get("appType")+""+map.get("appSubType"));
//			}
//		}

		try {
			saveUdpConnectionToEntityList(udpConnection,udpEntity);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			logger.error(e.getCause(), e);
		}

		//将每个XdrEntity加入XdrEntityList中，调用SaveHttpTransactionInfo的save方法保存到数据库中
		udpEntityList.add(udpEntity);

		/**
		 * Interface
		 * ProcedureStartTime
		 * ProcedureEndTime
		 * ProtocolType
		 * AppType
		 * AppSubType
		 * IPAddressType
		 * UserIPv4
		 * UserIPv6
		 * ......
		 *
		 *
		 */
		return udpEntityList;
	}

	public void saveUdpConnectionToEntityList(UdpConnection udpConnection,UdpEntity udpEntity) throws ParseException{

		if(udpConnection.al==null||udpConnection.al.size()==0)
			return;

		// 找到连接的connectionKey直接填写源地址和目的地址
		String[] connectionKey = udpConnection.connectionKey.split("-");
		String[] usersocket = connectionKey[0].split(":");
		String[] serversocket = connectionKey[1].split(":");

		String userIpv4;
		String userIpv6;
		Integer userPort;

		String appServerIpIpv4;
		String appServerIpIpv6;
		Integer appServerPort;

		if(usersocket.length>2) {
			//填写终端用户的ipv6地址和端口
			String[] useriplist = Arrays.copyOf(usersocket, usersocket.length-1);
			userIpv6 = String.join(":", useriplist);
			userPort =  Integer.valueOf(usersocket[8]);

			udpEntity.setUserIpv6(userIpv6);
			udpEntity.setUserPort(userPort);

			//填写ip_address_type,ipv4是0,ipv6是1。
			udpEntity.setIpAddressType(1);
		}
		else {
			//填写终端用户的ipv4地址和端口
			userIpv4 = usersocket[0];
			userIpv4 = userIpv4.replace("/", "");
			userPort = Integer.valueOf(usersocket[1]);

			udpEntity.setUserIpv4(userIpv4);
			udpEntity.setUserPort(userPort);

			//填写ip_address_type,ipv4是0,ipv6是1。
			udpEntity.setIpAddressType(0);
		}


		// 填写L4 Protocol,0为tcp,1为udp
		udpEntity.setL4Protocal(1);

		if(serversocket.length>2) {
			//填写服务端用户的ipv6地址和端口
			String[] appserveriplist = Arrays.copyOf(serversocket, serversocket.length-1);
			appServerIpIpv6 = String.join(":", appserveriplist);
			appServerPort =  Integer.valueOf(serversocket[8]);

			udpEntity.setAppServerIpIpv6(appServerIpIpv6);
			udpEntity.setAppServerPort(appServerPort);
		}
		else {
			//填写服务端用户的ipv4地址和端口
			appServerIpIpv4 = serversocket[0];
			appServerIpIpv4 = appServerIpIpv4.replace("/", "");
			appServerPort = Integer.valueOf(serversocket[1]);

			udpEntity.setAppServerIpIpv4(appServerIpIpv4);
			udpEntity.setAppServerPort(appServerPort);
		}

		Integer length = udpConnection.al.size();
		logger.debug("tcpConnection length:"+length);

		//计算procedure_start_time
		long timestamp_procedure_start_time = 0l;
		Date procedureStartTime = DateUtil.formatTimestamp(timestamp_procedure_start_time);
		udpEntity.setProcedureStartTime(procedureStartTime);

		//计算procedure_end_time
		long timestamp_procedure_end_time = 0l;
		Date procedureEndTime = DateUtil.formatTimestamp(timestamp_procedure_end_time);
		udpEntity.setProcedureEndTime(procedureEndTime);

		//填写interface
		Integer interFace = 11;
		udpEntity.setInterfaceCode(interFace);

		//填写payload
		//控制拿到payload的报文个数
		/*
		 * 从配置文件中拿payload个数
		 */
		Integer payloadNum = PacketAnalysisConfig.getConfigAsInt("tcp.payloads.num");
		byte[] payloads = new byte[]{};

		/*
		 * 根据配置文件，控制拿payload的个数
		 */
		Integer getPayloadLength = 0;
		if(payloadNum < udpConnection.al.size())
			getPayloadLength = payloadNum;
		else
			getPayloadLength = udpConnection.al.size();

		for(int i=0; i<getPayloadLength; i++) {
			byte[] temp = udpConnection.al.get(i).udpPacket.getPayload().getRawData();
			byte[] c = new byte[payloads.length+temp.length];
			System.arraycopy(payloads, 0, c, 0, payloads.length);
			System.arraycopy(temp, 0, c, payloads.length, temp.length);
			payloads = c;
		}
		//将二进制数组转为16进制字符串
		StringBuilder payloadstr = new StringBuilder(payloads.length*2);
		for(byte b:payloads){
			payloadstr.append(String.format("%02x",new Integer(b & 0xff)));
		}
		udpEntity.setPayload(payloadstr);
		udpEntity.setPayloadLength(payloadstr.length());

	}

}
